class Accommodation < ActiveRecord::Base
  
  validate :validate_cpfs, :verify_reservation, :validate_dates
  
  def verify_reservation
       reservation = Reservation.find_by_guest_cpf(guest_cpf)          
       if reservation.nil?
         self.find_avaialable_room
       else
        room = Room.find_by_num(reservation.room_id)
        room.update_attribute(:empty, false)
        room.update_attribute(:reserved,false)        
        self.room_num =  room.num
        Reservation.delete(reservation.id)
       end   
  end
  
  def find_avaialable_room  
  room = Room.find_empty_room(num_persons)
  if room.nil?
    errors.add("no room avaialable")
  else
    self.room_num = room.num
    room.empty = false
    room.update_attribute(:empty, false)
  end   
end
  
  def validate_cpfs
    guest = Guest.find_by_cpf(guest_cpf)
    employee = Employee.find_by_cpf(emp_cpf)
    if guest.nil?
      errors.add(:guest_cpf,"not registered")
    end
    if employee.nil?
      errors.add(:emp_cpf,"not registered")
    end
  end  
  
  def validate_dates
   date = Date.new
   if(arrive_date.to_s > exit_date.to_s)
    errors.add("Date choice")
  else
    if(not (arrive_date == Date.today))
      errors.add("Date choice")
    end  
   end
 end
  
  
end